package com.web3.management.service;

import com.web3.management.dto.response.OperationLogResponse;
import com.web3.management.entity.OperationLog;
import com.web3.management.repository.OperationLogRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 操作日志服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OperationLogService {

    private final OperationLogRepository operationLogRepository;

    public void record(String operationType, String targetType, Integer targetId, String description) {
        OperationLog logEntity = new OperationLog();
        logEntity.setOperationType(operationType);
        logEntity.setTargetType(targetType);
        logEntity.setTargetId(targetId);
        logEntity.setDescription(description);
        operationLogRepository.save(logEntity);
        log.info("记录操作日志: {} - {}", operationType, description);
    }

    public List<OperationLogResponse> getRecentLogs(int limit) {
        Pageable pageable = PageRequest.of(0, limit);
        List<OperationLog> logs = operationLogRepository.findByOrderByCreatedAtDesc(pageable);
        return logs.stream().map(this::convert).collect(Collectors.toList());
    }

    private OperationLogResponse convert(OperationLog log) {
        OperationLogResponse response = new OperationLogResponse();
        response.setId(log.getId());
        response.setOperationType(log.getOperationType());
        response.setTargetType(log.getTargetType());
        response.setTargetId(log.getTargetId());
        response.setDescription(log.getDescription());
        response.setCreatedAt(log.getCreatedAt() != null ? log.getCreatedAt() : new Date());
        return response;
    }
}
